import { getRequest } from "@/api/request";
import { AxiosResponse } from "axios";
import { translateCount } from "@/utils/util";

interface Query {
  id: string | number | undefined;
  offset: number;
  limit: number;
}

export interface Info {
  coverImgUrl: string;
  playCount: string;
  name: string;
  nickname: string;
  avatarUrl: string;
}
const REQUEST_URL = {
  playlist: "/playlist/detail",
  playlistComment: "/comment/playlist",
};

const handleList = (res: AxiosResponse) => {
  const info: Info = {
    coverImgUrl: res.data.playlist.coverImgUrl,
    playCount: translateCount(res.data.playlist.playCount),
    name: res.data.playlist.name,
    nickname: res.data.playlist.creator.nickname,
    avatarUrl: res.data.playlist.creator.avatarUrl,
  };
  const list = res.data.playlist.tracks.map((it: any) => {
    return {
      name: it.name,
      picUrl: it.al.picUrl,
      id: it.id,
      songName: it.ar[0].name,
    };
  });
  return {
    info,
    list,
  };
};

const handleComment = (res: AxiosResponse) => {
  if (res.data.comments) {
    const CommentList = res.data.comments.map((it) => {
      return {
        commentId: it.commentId,
        userImg: it.user.avatarUrl,
        userName: it.user.nickname,
        date: it.timeStr,
        likeNum: it.likedCount,
        content: it.content,
        repliesNum: it.beReplied.length,
      };
    });
    return CommentList;
  } else {
    return [];
  }
};

export const getPlayList = (id: number | string | undefined) => {
  return getRequest(REQUEST_URL.playlist + `?id=${id}`).then(handleList);
};

export const getPlayListComment = (query: Query) => {
  return getRequest(
    REQUEST_URL.playlistComment +
      `?id=${query.id}&limit=${query.limit}&offset=${query.offset}`
  ).then(handleComment);
};
